<template>
    <div class="app-container">
        <!-- <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form> -->

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['SYSConfig:factory:add']"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['SYSConfig:factory:edit']"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['SYSConfig:factory:remove']"
                >删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['SYSConfig:factory:export']"
                >导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <t-ag-grid
          :style="{height: height}"
          :column-defs="column"
          :row-data="factoryList"
          :row-buffer="20"
          row-selection="multiple"
          :suppress-row-click-selection="true"
          :row-multi-select-with-click="true"
          align="center"
          header-align="center"
          :defaultColDef = "{
              menuTabs: ['filterMenuTab', 'columnsMenuTab']
          }"
          @selection-changed="selectionChanged"
          />

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改车间对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="factoryRef" :model="form" :rules="rules" label-width="80px">
              <el-form-item label="车间ID" prop="factoryId">
                  <el-input v-model="form.factoryId" placeholder="请输入车间ID" :disabled="title === '修改'"/>
              </el-form-item>
              <el-form-item label="工厂描述" prop="factoryDes">
                  <el-input v-model="form.factoryDes" placeholder="请输入工厂描述" />
              </el-form-item>
              <el-form-item label="基地" prop="siteId">
                <el-select v-model="siteValue" placeholder="Select">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Factory">
  import { listFactory, getFactory, delFactory, addFactory, updateFactory, listFactorySite } from "@/api/SYSConfig/factory"

  const { proxy } = getCurrentInstance()
  const { oee_b_factory } = proxy.useDict('oee_b_factory')

  const factoryList = ref([])
  const open = ref(false)
  const loading = ref(true)
  const showSearch = ref(true)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const total = ref(0)
  const title = ref("")

  const options = ref([])
  const siteValue = ref(undefined)

  const height = ref('calc(100% - 65px)')

  const column = [
    { headerName: "车间ID", field: "factoryId", headerCheckboxSelection: true, checkboxSelection: true, minWidth: 100, flex: 1 },
    { headerName: "车间描述", field: "factoryDes", minWidth: 100, flex: 1 },
    { headerName: "基地", field: "siteId", minWidth: 100, flex: 1 },
    { headerName: "创建人", field: "createUser", minWidth: 100, flex: 1 },
    { headerName: "创建时间", field: "createTime", minWidth: 100, flex: 1 },
    { headerName: "更新人", field: "updateUser", minWidth: 100, flex: 1 },
    { headerName: "更新时间", field: "updateTime", minWidth: 100, flex: 1 }
  ]

  column.forEach((item) => {
    item.filter = 'agMultiColumnFilter'
  })

  const gridApi = ref()

  const selectionChanged  = (params) => {
    gridApi.value = params.api
    const selectedRows = params.api.getSelectedRows()
    single.value = selectedRows.length !== 1
    multiple.value = !selectedRows.length
  }

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10000,
      factoryId: null
    },
    rules: {
    }
  })

  const { queryParams, form, rules } = toRefs(data)

  /** 查询车间列表 */
  function getList() {
    loading.value = true
    listFactory(queryParams.value).then(response => {
      factoryList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }

  // 取消按钮
  function cancel() {
    open.value = false
    reset()
  }

  // 表单重置
  function reset() {
    form.value = {
      factoryId: [],
      factoryDes: null,
      siteId: [],
      createUser: null,
      createTime: null,
      updateUser: null,
      updateTime: null
    }
    options.value = []
    proxy.resetForm("factoryRef")
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
  }

  const getOptions = () => {
    console.log(8989, title.value)
    listFactorySite().then((res) => {
      res.rows.forEach((item) => {
        if(options.value.indexOf(item.siteId) === -1){
          options.value.push({
            label: item.siteId,
            value: item.siteId
          })
        }
      })
      // siteValue.value =  options.value[0] ? options.value[0].value : undefined
    })
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset()
    open.value = true
    title.value = "新增"
    getOptions()
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset()
    const _factoryId = gridApi.value.getSelectedRows()[0].factoryId
    getFactory(_factoryId).then(response => {
      form.value = response.data
      siteValue.value = response.data.siteId
      // form.value.factoryId = form.value.factoryId.split(",")
      // form.value.siteId = form.value.siteId.split(",")
      open.value = true
      title.value = "修改"
    })
    getOptions()
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["factoryRef"].validate(valid => {
      if (valid) {
        // form.value.factoryId = form.value.factoryId.join(",")
        // form.value.siteId = form.value.siteId.join(",")
        if (title.value === '修改') {
          form.value.siteId = siteValue.value
          updateFactory(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          })
        } else {
          form.value.siteId = siteValue.value
          addFactory(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
        }
      }
    })
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _factoryIds = []
    gridApi.value.getSelectedRows().map(item => _factoryIds.push(item.factoryId) )
    proxy.$modal.confirm('是否确认删除车间编号为"' + _factoryIds + '"的数据项？').then(function() {
      return delFactory(_factoryIds)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => {})
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('SYSConfig/factory/export', {
      ...queryParams.value
    }, `factory_${new Date().getTime()}.xlsx`)
  }

  getList()
</script>
